<template>
  <div class="container project">
    <div class="tree">
      <catalog
        :props="data.deptTreeProps"
        :tree-data="store.state.projectCenter.orgList"
        :default-expanded-keys="data.defaultExpandedKeys"
        @on-search="orgSearch"
      />
    </div>
    <div class="data">
      <el-row class="header">
        <el-col class="asd" :span="14" align="left">
          <el-select clearable v-model="data.params.projectCategory" placeholder="全部项目">
            <el-option
              v-for="item in store.state.projectCenter.projectDict.KHGL_XMZL_PROJECT_TYPE"
              :key="item.itemValue"
              :label="item.itemText"
              :value="item.itemValue"
            />
          </el-select>
          <el-input
            clearable
            v-model="data.params.projectName"
            placeholder="项目名称/编号"
            style="width: 200px; margin-right: 15px"
          />
          <el-button class="ordinary" @click="handleSearch()">搜索</el-button>
        </el-col>
        <el-col class="asd" :span="10" align="right">
          <el-button v-limit="'XMZX:XMGL:XMBG:EXPORT'" class="ordinary" @click="handleExport()"
            >批量导出</el-button
          >
          <!-- <el-button v-limit="'XMZX:XMGL:XMBG:EXAMINE'" type="primary" @click="handleExamine()"
            >变更审批</el-button
          > -->
        </el-col>
      </el-row>

      <Table
        :hasOperate="false"
        :loading="data.isLoading"
        :table-arr="data.allTableData"
        :columns="data.columns"
        :page-size="data.params.size"
        :page-num="data.params.current"
        @selectList="getCurrentList"
        @row-click="handleRowClick"
      >
        <template #status>
          <el-table-column label="状态" width="100">
            <template #default="scope" class="status">
              <span class="draft" v-if="scope.row.status == 0">草稿</span>
              <span class="pending" v-if="scope.row.status == 1">待审批</span>
              <span class="approved" v-if="scope.row.status == 2">正常办结</span>
              <span class="rejection" v-if="scope.row.status == 3">已退回</span>
              <span class="rejection" v-if="scope.row.status == 4">已撤办</span>
              <span class="rejection" v-if="scope.row.status == 5">强制办结</span>
              <span class="rejection" v-if="scope.row.status == 6">已废弃</span>
              <span class="rejection" v-if="scope.row.status == 7">已挂起</span>
              <span class="rejection" v-if="scope.row.status == 8">已驳回</span>
            </template>
          </el-table-column>
        </template>
        <template #operate="{ row }">
          <el-button
            v-limit="'XMZX:XMGL:XMBG:EDIT'"
            :disabled="!(row.status == 0 || row.status == 8)"
            class="ordinary"
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-limit="'XMZX:XMGL:XMBG:DETAIL'"
            size="small"
            class="ordinary"
            @click="handleDetail(row)"
            >详情</el-button
          >
          <el-button
            v-if="row.status == 1 && row.currUserId.split(',').includes(data.username)"
            v-limit="'XMZX:XMGL:XMBG:EXAMINE'"
            type="primary"
            @click="handleExamine(row)"
            >审批</el-button
          >
        </template>
      </Table>
      <div class="example-pagination-block">
        <el-pagination
          background
          layout="prev, pager, next ,total,sizes,jumper"
          :total="data.total"
          :page-size="data.params.size"
          v-model:current-page="data.params.current"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
      <!-- 项目变更编辑详情对话框 -->
      <!-- <el-dialog v-model="data.editDialog" width="60%" :title="data.currentHandle">
        <change :title="data.currentHandle" ref="changeForm" v-if="data.editDialog"></change>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.editDialog = false">关闭</el-button>
            <el-button
              v-if="data.currentHandle == '项目变更编辑'"
              type="primary"
              @click="handleSubmit()"
              >提交</el-button
            >
          </span>
        </template>
      </el-dialog> -->

      <!-- 项目变更审批表格 -->
      <el-dialog
        v-model="data.editDialog"
        width="60%"
        top="10vh"
        :title="data.currentHandle"
        @close="handleClose"
      >
        <el-tabs v-model="activeName" class="demo-tabs box">
          <el-tab-pane label="基本信息" name="1">
            <change v-if="data.editDialog" :title="data.currentHandle" ref="changeForm"></change>
            <!-- <examine v-if="data.editDialog"></examine> -->
          </el-tab-pane>
          <el-tab-pane
            label="流程图"
            name="2"
            v-if="data.currentHandle != '项目变更编辑' && data.currentRow.status != 0"
          >
            <flowChart
              v-if="data.editDialog"
              :processInstanceId="data.processInstanceId"
            ></flowChart>
          </el-tab-pane>
        </el-tabs>
        <template #footer>
          <div
            class="dialog-footer"
            style="float: left"
            v-if="data.currentHandle == '项目变更审批'"
          >
            <el-form label-width="120px" :rules="rules" ref="ruleFormRef" :model="ruleForm">
              <el-form-item label="审批意见" prop="comment">
                <el-input
                  type="textarea"
                  placeholder="审批意见"
                  v-model="ruleForm.comment"
                  style="width: 450px; margin-top: -10px"
                  clearable
                />
              </el-form-item>
            </el-form>
          </div>
          <span class="dialog-footer">
            <el-button @click="data.editDialog = false">关闭</el-button>
            <el-button
              v-if="data.currentHandle == '项目变更编辑'"
              type="primary"
              @click="handleSubmit(0)"
              >保存</el-button
            >
            <el-button
              v-if="data.currentHandle == '项目变更编辑'"
              type="primary"
              @click="handleSubmit(1)"
              >提交</el-button
            >
            <el-button
              v-if="data.currentHandle == '项目变更审批'"
              type="danger"
              @click="handleNoPass()"
              >审批驳回</el-button
            >
            <el-button
              v-if="data.currentHandle == '项目变更审批'"
              type="primary"
              @click="handlePass()"
              >审批通过</el-button
            >
          </span>
        </template>
      </el-dialog>

      <!-- 导出字段选择 -->
      <Export
        :detailList="data.detailList"
        :showing="data.exportDialog"
        @close="closeExport"
        @handle-filed="handleFiled"
      ></Export>
      <el-dialog
        v-model="data.dealVisible"
        title="系统正在处理中....."
        width="40%"
        top="14%"
        height="400"
        :show-close="false"
        :close-on-click-modal="false"
      >
        <el-alert
          type="success"
          :closable="false"
          style="margin-bottom: 20px"
          description="当前流程正在处理中,请稍等……"
        >
        </el-alert>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts">
import { reactive, ref } from 'vue'
import tableData from './tableHeader.json'

import {
  exportChangeProjectList,
  getChangeList,
  getDetailById,
  submitProjectChange,
} from '../../api/project'
import Catalog from '../../components/Catalog/index.vue'
import { getOrgTree } from '../../api/org'
import Table from '../../components/table2/table.vue'
import change from './components/change.vue'
import flowChart from '@/components/PublicProcess/Chart/flowChart.vue'
import Export from '@/views/project/components/Export/index.vue'

import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { allowProcess, refuseProcess, startProcess } from '../../api/commom'
import { servicesLoading } from '@/utils/loading'

export default {
  components: {
    Catalog,
    Table,
    change,
    flowChart,
    Export,
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    const changeForm = ref()
    let data = reactive({
      defaultExpandedKeys: [],
      tableTreeData: [],
      currentHandle: '',
      params: {
        createOrgId: '',
        projectName: '',
        projectCategory: '',
        current: 1,
        size: 10,
      },
      isLoading: false,
      allTableData: [],
      columns: tableData.platformTableHeader,
      total: 0,
      processInstanceId: '',
      currentList: [] as any,
      ids: [],
      editDialog: false,
      currentRow: {} as any,
      dealVisible: false,
      deptTreeProps: {
        label: 'name',
        children: 'children',
      },
      exportDialog: false,
      detailList: [] as any,
      username : JSON.parse(localStorage.getItem('userInfo') as any).username
    })
    const ruleFormRef = ref()
    const ruleForm = reactive({
      comment: '',
    })
    const rules = reactive({
      comment: [{ required: true, message: '请输入审批意见', trigger: 'change' }],
    })
    const onSearch = async () => {
      data.isLoading = true
      getChangeList(data.params).then((res) => {
        if (res.data.code == 200) {
          let result = res.data.data
          result.records.map(async (item) => {
            item.startTime = item.startTime?.slice(0, 10)
            item.endTime = item.endTime?.slice(0, 10)
            item.applicationTime = item.applicationTime?.slice(0, 10)
            if (item.type == 1) {
              item.typeName = '负责人变更'
            } else if (item.type == 2) {
              item.typeName = '项目内容变更'
            } else if (item.type == 3) {
              item.typeName = '承接单位变更'
            }
            if (item.projectCategory == 1) {
              item.projectCategoryName = '科技研发项目'
            } else if (item.projectCategory == 2) {
              item.projectCategoryName = '数字化项目'
            }
          })
          data.allTableData = result.records
          data.total = result.total
          data.isLoading = false
        }
      })
    }
    onSearch()

    const handleSearch = () => {
      data.params.current = 1
      onSearch()
    }
    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.currentList = currentList
      data.ids = currentList.map((item) => {
        return item.id
      })
    }
    getOrgTree().then((res) => {
      data.tableTreeData = res.data.data
      // this.treeSelectData[0].children = this.dictCatalog
      // data.defaultExpandedKeys = (data.tableTreeData as any).map((item) => item.id)
    })
    //改变页码
    const handleCurrentChange = (e) => {
      console.log(e, 'handleCurrentChange')
      data.params.current = e
      onSearch()
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      console.log(e, 'handleSizeChange')
      data.params.size = e
      onSearch()
    }
    const orgSearch = (org) => {
      data.params.current = 1
      data.params.createOrgId = org.id
      onSearch()
    }
    //编辑提交流程对话框
    const handleEdit = (row) => {
      data.currentRow = row
      const loading = servicesLoading({ fullscreen: false })
      getDetailById({
        id: row.id,
      })
        .then((res) => {
          loading.close()
          const resData = res.data.data
          console.log(resData, 'resData')
          for (let key in store.state.projectCenter.changeForm) {
            store.state.projectCenter.changeForm[key] = resData[key]
          }
          data.currentHandle = '项目变更编辑'
          data.editDialog = true
        })
        .catch(() => {
          loading.close()
          ElMessage({
            message: '服务器错误',
            type: 'warning',
          })
        })
    }
    const handleRowClick = (row) => {
      handleDetail(row)
    }
    const handleDetail = (row) => {
      data.currentRow = row
      const loading = servicesLoading({ fullscreen: false })
      getDetailById({
        id: row.id,
      })
        .then((res) => {
          loading.close()
          const resData = res.data.data
          console.log(resData, 'resData')
          data.processInstanceId = resData.processInstanceId ? resData.processInstanceId : ''
          for (let key in store.state.projectCenter.changeForm) {
            store.state.projectCenter.changeForm[key] = resData[key]
          }
          data.currentHandle = '项目变更详情'
          data.editDialog = true
        })
        .catch(() => {
          loading.close()
          ElMessage({
            message: '服务器错误',
            type: 'warning',
          })
        })
    }

    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          exportChangeProjectList({ ...data.params, ids: data.ids, headList: arr })
          console.log('批量导出')
          data.exportDialog = false
        })
      }
    }
    const handleExport = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'projectYear', title: '立项年份' },
        { fieldName: 'projectCategoryName', title: '项目类型' },
        { fieldName: 'affiliatedUnitName', title: '所属单位' },
        { fieldName: 'startTime', title: '项目开始时间' },
        { fieldName: 'endTime', title: '项目结束日期' },
        { fieldName: 'typeName', title: '变更类型' },
        { fieldName: 'beforeContent', title: '变更前内容' },
        { fieldName: 'afterContentName', title: '变更后内容' },
        { fieldName: 'description', title: '变更事由' },
        { fieldName: 'applicantName', title: '申请人' },
        { fieldName: 'applicationTime', title: '申请时间' },
      ]
    }
    // const handleExport = () => {
    //   console.log('批量导出')
    //   exportChangeProjectList({ ...data.params, ids: data.ids })
    // }

    // 处理不通过,提交的过程中.......
    let deal = (id, state) => {
      let times = setInterval(() => {
        getDetailById({
          id: id,
        }).then((res) => {
          const resData = res.data.data
          console.log(
            resData.status == state,
            state == 2 && resData.status == 1,
            'state == 2 ? 1 || 2 : state'
          )
          if (resData.status == state || (state == 2 && resData.status == 1)) {
            data.dealVisible = false
            onSearch()
            ElMessage({
              message: '流程办理成功',
              type: 'success',
            })
            clearTimeout(times)
          }
        })
      }, 3000)
    }
    //保存编辑项目变更申请
    //提交项目变更申请，启动流程
    const handleSubmit = (index: number) => {
      changeForm.value.submitForm().then((res) => {
        console.log(res)
        submitProjectChange({
          ...store.state.projectCenter.changeForm,
        }).then((res) => {
          if (res.data.code == 200) {
            // data.editDialog = false
            if (index == 1) {
              //提交项目变更申请，启动流程
              // data.editDialog = false
              ElMessageBox.confirm('确认提交该项目变更申请吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
              }).then(() => {
                data.editDialog = false
                const loading = servicesLoading({ fullscreen: true })
                startProcess({
                  flowKey: 'change-project',
                  businessKey: data.currentRow.id,
                  businessType: 'YW18',
                  random: new Date().valueOf(),
                }).then((res) => {
                  loading.close()
                  if (res.data.code != 200) {
                    ElMessage({
                      message: '流程启动失败,请稍后重试',
                      type: 'warning',
                    })
                  } else {
                    data.dealVisible = true
                    deal(data.currentRow.id, 1)
                  }
                })
              })
            } else {
              data.editDialog = false
              ElMessage({
                message: '保存成功',
                type: 'success',
              })
            }
          }
        })
      })
    }
    //审批变更申请，处理流程
    const handleExamine = (row) => {
      console.log(row,'row');
      data.currentRow = row
      const loading = servicesLoading({ fullscreen: false })
      //获取对应流程processInstanceId,渲染流程图
      getDetailById({
        id: row.id,
      }).then((res) => {
        const resData = res.data.data
        console.log(resData, 'resData')
        data.processInstanceId = resData.processInstanceId
          ? resData.processInstanceId
          : '4eefd59d-6998-11ee-b595-525400c6fca2'
        for (let key in store.state.projectCenter.changeForm) {
          store.state.projectCenter.changeForm[key] = resData[key]
        }
        data.currentHandle = '项目变更审批'
        data.editDialog = true
        loading.close()
      })
    }
    //审批通过
    const handlePass = () => {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          ElMessageBox.confirm('确认通过本次申请吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            handleResult(allowProcess, 2)
          })
        }
      })
    }
    //审批驳回
    const handleNoPass = () => {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          ElMessageBox.confirm('确认驳回本次申请吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            handleResult(refuseProcess, 8)
          })
        }
      })
    }
    const handleResult = (handleProcess, status) => {
      const loading = servicesLoading({ fullscreen: true, text: '正在请求流程' })
      handleProcess({
        procInsId: data.processInstanceId,
        comment: ruleForm.comment,
        flowKey: 'change-project',
        businessKey: data.currentRow.id,
        businessType: 'YW18',
        random: new Date().valueOf(),
      })
        .then((res) => {
          loading.close()
          if (res.data.code == 200) {
            data.editDialog = false
            data.dealVisible = true
            deal(data.currentRow.id, status)
          } else {
            ElMessage({
              message: res.data.message,
              type: 'warning',
            })
          }
        })
        .catch(() => {
          loading.close()
        })
    }
    const handleClose = () => {
      console.log('对话框关闭了')
      data.editDialog = false
      activeName.value = '1'
      if (data.currentHandle == '项目变更审批') {
        ruleFormRef.value.resetFields()
      }
    }

    return {
      store,
      rules,
      ruleForm,
      ruleFormRef,
      changeForm,
      data,
      activeName,
      getCurrentList,
      handleCurrentChange,
      handleSizeChange,
      onSearch,
      handleSearch,
      handleEdit,
      handleDetail,
      handleRowClick,
      handleExamine,
      handleSubmit,
      handleClose,
      closeExport,
      handleFiled,
      handleExport,
      orgSearch,
      handlePass,
      handleNoPass,
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
}
.project {
  display: flex;
  .tree {
    width: 20%;
  }
  .data {
    width: 80%;
  }
}
.pageName {
  font-weight: 700;
}

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}
.box {
  :deep(.el-tabs__content) {
    max-height: 200px;
    overflow-y: auto;
  }
}
/deep/.demo-tabs > .el-tabs__content {
  max-height: 500px;
  overflow-y: auto;
}
:deep(.el-dialog__body) {
  display: block;
  padding: 10px 20px;
}
:deep(.el-dialog__header) {
  border-bottom: 1px solid rgb(234, 230, 230);
}
.example-pagination-block {
  margin-top: 15px;
  text-align: center;
}
</style>
